'use strict';

const path = require('path');

const inquirer = require('inquirer');
const fsExtra = require('fs-extra');
const ora = require('ora');

const Command = require('@x3-cli-dev/command');
const log = require('@x3-cli-dev/log');

const CACHE_DIR = 'dependencies';
const TEMPLATE_DIR = 'templates';

class CleanCommand extends Command {
  init() {
    this.template = !!this._options.template;
    this.force = !!this._options.force;
    log.verbose('template', this.template);
    log.verbose('force', this.force);
  }

  async exec() {
    try {
      await this.clear();
    } catch (error) {
      log.error(error.message);
      if (process.env.LOG_LEVEL === 'verbose') {
        console.log(error);
      }
    } finally {
      process.exit(0);
    }
  }

  async clear() {
    const clearFn = async () => {
      const dependenciesPath = path.join(process.env.X3_CLI_HOME_PATH, CACHE_DIR);
      const templatePath = path.join(process.env.X3_CLI_HOME_PATH, TEMPLATE_DIR);
      log.verbose('cachePath', dependenciesPath);
      log.verbose('templatePath', templatePath);
      const spinner = ora('开始清楚缓存').start();
      try {
        await fsExtra.emptyDir(dependenciesPath);
        if (this.template) {
          await fsExtra.emptyDir(templatePath);
        }
        spinner.succeed('清除缓存成功');
      } catch (error) {
        spinner.fail('清楚缓存失败');
        throw error;
      }
    }

    if (this.force) {
     await clearFn();
    } else {
      const { isContinue } = await inquirer.prompt({
        name: 'isContinue',
        type: 'confirm',
        message: '确认清除缓存吗?',
        default: false,
      });
      if (isContinue) {
        await clearFn();
      }
    }
  }
}

function clean(argv) {
  return new CleanCommand(argv);
}

module.exports = clean;
module.exports.CleanCommand = CleanCommand;
